package com.estronger.shopmanage.ui.install.pg;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B33BuildNum;
import com.estronger.shopmanage.bean.InstallDPG;
import com.estronger.shopmanage.fragment.FragmentFactory;
import com.estronger.shopmanage.fragment.install.pg.InstallPGBaseFragment;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.batchpg.BatchPgActivity;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.view.XinShouYindao.HoleBean;
import com.estronger.shopmanage.view.XinShouYindao.NewbieGuideManager;
import com.estronger.shopmanage.view.floatactionbutton.MyCoordinatorLayout;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.NoDoubleClickUtils;
import com.viewpagerindicator.TabPageIndicator;

/**
 * 安装任务-派工
 */
public class InstallPGActivity extends BaseActivity {

    private final int CODE_TO_BATCHPGACTIVITY3 = 1003;//跳转批量派工
    private ViewPager mainVP;
    private Activity mActivity;
    public static InstallDPG.Datas.InstallDPGListData idpData = null;
    public static int CALL_RESULT_MSCONDITION = -3;//电话结束后跳转“测量条件确认”
    public static int CALL_RESULT_PGSURE = -4;//电话结束后跳转“派工确认”
    // onActivityResult时 -SEND_CALL-代表电话结束后返回，-REFLESH_DATA-代表从其他界面返回要刷新界面
    public static int SEND_CALL = 10000, REFLESH_DATA = 5000;
    private MyCoordinatorLayout rl_root;// 根布局view
    private TabPageIndicator indicator;// 页面的title布局
    private TextView tv_title;
    private TextView tv_title_right;//批量派工
    private int currPosition = 0;// 当前显示页面得位置
    // 对应每个页的位置-标题
    private String[] pos = {"0", "1"};
    private String[] titleString = {"待派工(0)", " 已派工  "};
    private String[] titleString2 = {"待派工", " 已派工 "};
    private FloatingActionButton fab;

    // 初始化各个View
    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rl_root = (MyCoordinatorLayout) View.inflate(this,
                R.layout.activity_install_pg, null);
        setContentView(rl_root);
        mActivity = InstallPGActivity.this;

        mainVP = (ViewPager) findViewById(R.id.main_vp);
        indicator = (TabPageIndicator) findViewById(R.id.category_strip);
        tv_title = (TextView) findViewById(R.id.measure_title);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        tv_title.setText("安装任务");
        tv_title_right = findViewById(R.id.tv_title_right);
        tv_title_right.setVisibility(View.VISIBLE);
        tv_title_right.setText("批量派工");
        tv_title_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!NoDoubleClickUtils.isDoubleClick())
                    BatchPgActivity.startTActivity(mActivity, 3, CODE_TO_BATCHPGACTIVITY3);
            }
        });
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(InstallPGActivity.this, InstallPGTripActivity.class));
            }

            ;
        });

        if (PrefUtils.getBoolean(this, "isFirstLogin", false)) {
            /**
             * 显示新手引导             *
             * **/
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    new NewbieGuideManager(InstallPGActivity.this, NewbieGuideManager.TYPE_LIST, "点这可以查看安装师行程哦!").addView(fab, HoleBean.TYPE_CIRCLE).show();
                }
            }, 50);
            PrefUtils.setBoolean(this, "isFirstLogin", false);
        }
        ;

    }

    // 获取待安装数量
    public void getTitleNum() {
        MyHandler myHandle = new MyHandler();
        Message msg = new Message();
        myHandle.handleMessage(msg);

    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            RequestParams params = new RequestParams();
            params.addBodyParameter("sf_action", "istgettasklistnum");
            params.addBodyParameter("usercode", MyApplication.getUserCode());
            connect(params, NetManager.INSTALL_DAINUM);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //zhusuibo 20170721 11：33改的
        if (MyApplication.isNeedToReflash_inst) {
            FragmentFactory.createInstallPGFragment(getCurrPosition()).connect(
                    pos[getCurrPosition()], true);
            MyApplication.isNeedToReflash_inst = false;
        }
        getTitleNum();
    }

    // 主要是做子页面切换的监听事件
    @Override
    protected void initAction() {
        indicator.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(final int position) {
                currPosition = position;
                MyApplication.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        FragmentFactory.createInstallPGFragment(position).connect(
                                pos[position], true);
                    }
                }, 500);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        mainVP.setAdapter(new InstallPGAdpater(getSupportFragmentManager()));
        indicator.setViewPager(mainVP);
        indicator.onPageSelected(0);
        indicator.setSmoothScrollingEnabled(true);
    }

    public int getCurrPosition() {
        return currPosition;
    }

    /**
     * @param position 哪个页面 0-2
     * @param size     页面里有多少条目
     */
    public void setIndicatorTitle(int position, String size) {
        LinearLayout layout = ((LinearLayout) indicator.getChildAt(0));
        TextView tv = (TextView) (layout.getChildAt(position));
        tv.setText(titleString2[position] + "(" + size + ")");
    }

    // 送货下面四个fragment的适配器
    private class InstallPGAdpater extends FragmentStatePagerAdapter {
        public InstallPGAdpater(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titleString[position];
        }

        @Override
        public InstallPGBaseFragment getItem(int position) {
            InstallPGBaseFragment fragment = FragmentFactory.createInstallPGFragment(position);
            return fragment;
        }

        @Override
        public int getCount() {
            return titleString.length;
        }
    }

    @Override
    protected void onDestroy() {
        FragmentFactory.clearinstallpg();
        super.onDestroy();
    }

    /*
     * 每次联网成功都会调用，根据code区别请求的sf_action
     *
     * @see BaseActivity#onNetSuccess(int, java.lang.String)
     */
    @Override
    protected void onNetSuccess(int code, String result) {
        super.onNetSuccess(code, result);
        if (NetManager.INSTALL_DAINUM == code) {
            B33BuildNum bean = gson.fromJson(result, B33BuildNum.class);
            if (bean.success) {
                setIndicatorTitle(0, bean.data.notistnum);
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see FragmentActivity#onActivityResult(int, int, android.content.Intent)
     */
    public static String ctsName, ctsTime;

    @Override
    protected void onActivityResult(int request, int result, Intent arg2) {
        super.onActivityResult(request, result, arg2);
        if (request == CODE_TO_BATCHPGACTIVITY3) {
            if(result == Activity.RESULT_OK && arg2 != null){
                int isUpdate = arg2.getIntExtra("data_update", 0);
                if(isUpdate == 1){
                    FragmentFactory.createInstallPGFragment(getCurrPosition()).connect(
                            pos[getCurrPosition()], true);
                }
            }
        } else {
            if (CALL_RESULT_MSCONDITION == request /*|| SEND_CALL == request*/) {
                Intent intent = new Intent(this, InstallAffirmCondActivity.class);
                intent.putExtra("InstallItem", idpData);
                startActivityForResult(intent, REFLESH_DATA);
                CALL_RESULT_MSCONDITION = -3;
            }
            if (CALL_RESULT_PGSURE == request  /*|| SEND_CALL == request*/) {
                Intent intent1 = new Intent(this, InstallAffirmPGActivity.class);
                intent1.putExtra("InstallItem", idpData);
                startActivityForResult(intent1, REFLESH_DATA);
                CALL_RESULT_PGSURE = -4;
            }
            if (REFLESH_DATA == result || REFLESH_DATA == request) {
                FragmentFactory.createInstallPGFragment(getCurrPosition()).connect(
                        pos[getCurrPosition()], true);
            }
        }
    }
}
